<style>
	ul.ui-front{
		z-index: 200
	}
</style>
<input type="hidden" id="listid" value="<?php echo $_GET["planid"]?>">
<script type="text/javascript">
	function row_action_formater(cellvalue, options, rowObject)
	{
		
	// format the cellvalue to new format
		new_formated_cellvalue = "<a href=\"#\" onclick=\"openEditDialog('" + rowObject.id + "');return false\">Изменить</a>&nbsp;" +
					"<a href=\"#\">Удалить</a>"
		return new_formated_cellvalue;
	}
	$(document).ready(function () {
		//lert(1)
	$("#content_table").jqGrid({
	//url: "example.php",
		datatype: "local", //"xml",
		//mtype: "GET",
		colNames: ["Продукт","", "Кол-во", "ЕИ","Комментарии", ""],
		colModel: [
		{ name: "product", width: 270, align: "left" },
		{ name: "product_id",hidden:true },
		{ name: "volume", width: 70, align: "right" },
		{ name: "unit", width: 70, editable:true, align: "left"},
		{ name: "comment", width: 300, editable:true, align: "left"},
		{ name: "action", width: actionPaneWidth, formatter: formater_row_actions,
						formatoptions: {  }
		}
		],
		data:[
<?php
$c = "";
while ($row = $content_data["plan_details_ds"]->fetch_assoc()) {
	?>
	<?php echo $c ?>{"id" :"<?php echo $row['id'] ?>"
										, "product" :"<?php echo $row['product'] ?>"
										, "product_id" :"<?php echo $row['product_id'] ?>"
										, "unit":"<?php echo $row['unit'] ?>"
										, "comment":"<?php echo str_replace("\r\n","\\n",$row['comment']) ?>"
										, "volume" :"<?php echo number_format($row['volume'],1) ?>"
										, action:""}
	<?php
	$c = ",";
}
?>
		],
		pager: "#pager",
		//toppager:true,
		//cloneToTop:true,
		toolbar:[true,"top"],
		rowNum: 100,
		//rowcontent_table: [10, 20, 30],
		viewrecords: true,
		gridview: true,
		autoencode: true,
		//caption: "Редактировать запись",
		height:400,
		shrinkToFit:false,
		//editurl: "server.php",
		autowidth:true,
		//scroll:true,
		ondblClickRow:function(rowid, row, col, e){
		//alert(e);
			openEditDialog(rowid)
		//$(e.target).parent().css({color: "red"})
		}
	});
					jQuery("#content_table")
						.navGrid('#pager', {edit: false, add: false, del: false, search: false, refresh: false})
						.navButtonAdd('#pager', {
							caption: "Добавить",
							buttonicon: "ui-icon-plus",
							onClickButton: function () {
							openEditDialog(null)
							},
							position: "last"
						})
						.navButtonAdd('#pager', {
							caption: "Закрыть",
							buttonicon: "ui-icon-close",
							onClickButton: function () {
								closePlan();
							},
							position: "last"
						})
						.navButtonAdd('#t_content_table', {
							caption: "Печать",
							buttonicon: "ui-icon-print",
							onClickButton: function () {
								window.open("./print_plan.php?listid="+$("#listid").val())
							}/*,
							position: "last"*/
						})

					$("#edit_dialog").dialog({
						width: 400,
						modal: true,
						autoOpen: false,
						title: "Редактировать запись",
						buttons: [
						{
							text: "Сохранить",
							icons: {
								primary: "ui-icon-check"
							},
							click: function() {
								saveRecord();
							}

							// Uncommenting the following line would hide the text,
							// resulting in the label being used as a tooltip
							//showText: false
						},
						{
							text: "Отмена",
							icons: {
								primary: "ui-icon-close"
							},
							click: function() {
								cancelEdit();
							}

						}
					]
					});
					$("input[type=button]").button();
					//$( "select" ).combobox();
					$("#product").autocomplete({ minLength: 0,
						source: "action.php?action=searchProduct",
						appendTo:"body",
						focus: function(event, ui) {
						$("#project").val(ui.item.label);
										return false;
						},
						select: function(event, ui) {
							$("#product").val(ui.item.name);
							$("#product_id").val(ui.item.id);
							$( "#volume" ).spinner("option","step",ui.item.volume_increment);
							$( "#volume" ).val(ui.item.volume_increment)
							$( "#unit" ).val(ui.item.unit)
							return false;
						}
					}).autocomplete("instance")._renderItem = function(ul, item) {
					return $("<li>")
									.text(item.name)
									//.append( item.label )
									.appendTo(ul);
					}
	
					$("#volume").spinner({step:0.5});
	});
	
	var fieldIds = ["unit", "product","product_id","volume","comment"]
	function openEditDialog(id)
	{
		var row = $("#content_table").getRowData(id);
		$("#id").val(id)
		for (var i = 0; i < fieldIds.length; i++)
		{
			$("#" + fieldIds[i]).val(row[fieldIds[i]])
		}
		$("#edit_dialog").dialog("open");
	}
	function saveRecord()
	{
			$("#edit_dialog").dialog("close");
			$.ajax({
				type: "post",
				url: "action.php?" + $("#editForm").serialize(),
				data: {
					action: "savePlanItem",
					planid:"<?php echo $_GET["planid"]?>"
				},
				dataType: "json",
				error: function (q, w, e) {
				alert("All bed :(")
				},
				success: function (data) {
					if (data.status != "ok")
					{
						alert(data.error)
						return;
					}
					if ($("#id").val())
						jQuery("#content_table").jqGrid('setRowData', data.recordId, data.record);
					else
						jQuery("#content_table").jqGrid('addRowData', data.recordId, data.record);
				}
			})
	}
	function cancelEdit()
	{
		$("#edit_dialog").dialog("close");
	}
	function closePlan()
	{		
		if(!confirm("Закрыть текущий план?"))
			return;
		var name = prompt("Введите название нового плана", '')
		window.location.href="./action.php?action=closeplan&listid="+$("#listid").val()+"&planname="+encodeURIComponent(name);
	}

</script>
<div style="padding-top:2px 0;background-color:lightblue">
					<div class="ui-widget ui-widget-header ui-corner-top" style="padding:3px">
						Редактирование списка
					</div>
				</div>
<table id="content_table"><tr><td></td></tr></table> 
<div id="pager"></div> 


<div id="edit_dialog">
	<form id="editForm" style="margin: 0">
		<input type="hidden" name="id" id="id"/>

		<input type="text" name="product" id="product"/>
		<input type="hidden" name="product_id" id="product_id"/>
		<input type="text" name="volume" id="volume"/>
		
		<select name="unit" id="unit">
			<?php
			while ($row = $content_data["units_ds"]->fetch_assoc()) {
				?>
				<option id="<?php echo $row['unit'] ?>" title="<?php echo $row['description'] ?>"><?php echo $row['unit'] ?></option>
				<?php
			}
			?>
		</select>
		<textarea name="comment" id="comment" style="width:100%">
		
		</textarea>
		<!--table>
			<tr>
				<td class="edit_field_name">Продукт</td>
				<td class="edit_field"><input type="text" name="name" id="name"/></td>
			</tr>
			<tr>
				<td class="edit_field_name">Колчиество</td>
				<td class="edit_field"><input type="text" name="volume" id="volume"/></td>
			</tr>
			<tr>
				<td class="edit_field_name">Единица измерения</td>
				<td class="edit_field">
					<select name="unit" id="unit">
		<?php
		while ($row = $content_data["units_ds"]->fetch_assoc()) {
			?>
									<option id="<?php echo $row['unit'] ?>" title="<?php echo $row['description'] ?>"><?php echo $row['unit'] ?></option>
			<?php
		}
		?>
					</select>
				</td>
			</tr>

		</table-->
	</form>
	<!--input type="button" value="Сохранить" onclick="saveRecord()">
	<input type="button" value="Отменить" onclick="cancelEdit()"-->
</div>